package com.cssw.fyzb.core.dao.system;

import com.cssw.fyzb.core.model.dodb.SysFunc;
import com.cssw.fyzb.core.model.dodb.SysRole;
import com.cssw.fyzb.core.model.dodb.SysRoleFunc;
import com.ydn.dbframe.plugin.activerecord.Db;
import com.ydn.dbframe.plugin.activerecord.Page;
import com.ydn.dbframe.plugin.activerecord.parse.SqlParse;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author yangyiqun
 * @create 2020-08-10 11:09
 */
@Repository
public class RoleDaoImpl implements RoleDao {

    @Override
    public SysRole getById(Integer roleId) {
        return SysRole.dao.findById(roleId);
    }

    @Override
    public Page<SysRole> list(String roleName, int page, int limit) {
        Map param = new HashMap<>();
        param.put("roleName", roleName);
        SqlParse sqlParse = new SqlParse(param);

        sqlParse.addSQL("select t1.* ");
        sqlParse.addSQL(" from sys_role t1 where 1=1 ");
//        sqlParse.addLikeSQL(" and role_name like :roleName");
        sqlParse.addSQL(" order by create_time ");

        return SysRole.dao.paginate(page, limit, sqlParse);
    }

    @Override
    public void update(Long roleId, String roleName, String roleDesc, Long operId) {
        SysRole role = new SysRole();
        role.setRoleId(roleId);
        role.setRoleName(roleName);
        role.setRoleDesc(roleDesc);
        role.setUpdateTime(new Date());
        role.setUpdateOperId(operId);
        role.update();
    }

    @Override
    public void save(String roleName, String roleDesc, Long operId) {
        SysRole role = new SysRole();
        role.setRoleName(roleName);
        role.setRoleDesc(roleDesc);
        role.setCreateTime(new Date());
        role.setCreateOperId(operId);
        role.save();
    }


    @Override
    public void delete(Long roleId) {
        SysRole.dao.deleteById(roleId);
    }

    @Override
    public List<SysFunc> queryFuncByRoleId(Long roleId) {
        StringBuffer sql = new StringBuffer();
        sql.append(" select t1.*, ")
                .append("  (select count(1) from sys_role_func t2 where t2.role_id = ? and t2.func_id = t1.func_id) as cfgCnt ")
                .append(" from sys_func t1 where status = ? ");

        return SysFunc.dao.find(sql.toString(), roleId, SysFunc.STATUS_START);
    }

    @Override
    public void deleteRoleFuncByRoleId(Long roleId, Long operId) {
        Db.delete("delete from sys_role_func where role_id = ?", roleId);
    }

    @Override
    public void batchSaveRoleFunc(List<SysRoleFunc> roleFuncs) {
        Db.batchSave(roleFuncs, 100);
    }
}
